package cn.zhuangcloud.newversion.cas;

import cn.zhuangcloud.newversion.common.kit.TokenKit;
import cn.zhuangcloud.newversion.login.LoginInterceptor;
import cn.zhuangcloud.newversion.login.LoginService;
import cn.zhuangcloud.newversion.login.LoginValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.kit.Ret;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * 使用流程
 * 1.跳转到 //新庄云网/cas?redirect=设置token的地址
 * 登陆成功会发送包含token的请求到该地址，请自行设置token
 * 2.设置token后请返回如下格式文本
 * returnjs({"status":true,"redirect":"http://new.zhuangcloud.cn/"})
 * status:true/false登陆是否成功
 * redirect:如果登陆成功则跳转到该地址
 * 说明：
 * cas页面get请求的redirect接收url encode或原文
 * cookie服务器返回的json中的redirect只接受原文
 */

public class CasController extends Controller {

    private static final LoginService srv = LoginService.me;
    private static final Logger log = LoggerFactory.getLogger(CasController.class);

    @Before({CasInterceptor.class, GET.class})
    public void index() {
        renderTemplate("cas.html");
        String redirect = getPara("redirect");
        if(null==redirect){
            redirect("/login");
        }
    }

    @Before({GET.class,LoginValidator.class})
    public void doLogin() {
        String username = getPara("username");
        String password = getPara("password");
        String redirect = getPara("redirect");
        try {
            redirect=java.net.URLDecoder.decode(redirect,"utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e.toString(),e);
        }

        Ret ret=srv.login(username, password);
        String token=ret.getStr("token")==null?"":ret.getStr("token");
        redirect(redirect+"?token="+token);
    }

    public void cookie(){
        String token=getPara("token");
        setCookie(TokenKit.COOKIEID,token,3600);
        renderHtml("returnjs({\"status\":true,\"redirect\":\"http://javaweb.yangzhizhuang.net/\"})");
    }

}
